#include <REGX52.H>
#include "Delay.h"

#define LCD1602_DataPort P0
sbit LCD1602_RS = P1^0;
sbit LCD1602_RW = P1^1;
sbit LCD1602_EN = P1^5;

void LCD1602_WriteCommand(unsigned char Command)
{
    LCD1602_RS = 0;
    LCD1602_RW = 0;
    LCD1602_DataPort = Command;
    LCD1602_EN = 1;
    LCD1602_EN=0;
}

void LCD1602_WriteData(unsigned char Data)
{
    LCD1602_RS = 1;
    LCD1602_RW = 0;
    LCD1602_DataPort = Data;
    LCD1602_EN = 1;
    LCD1602_EN = 0;

}

void LCD1602_ReadFlag(unsigned char *Flag)
{
    LCD1602_RS = 0;
    LCD1602_RW = 1;
    LCD1602_EN = 1;
    *Flag = LCD1602_DataPort;
    LCD1602_EN = 0;
}

void LCD1602_ReadData(unsigned char *Data)
{
    LCD1602_RS = 1;
    LCD1602_RW = 1;
    LCD1602_EN = 1;
    *Data = LCD1602_DataPort;
    LCD1602_EN = 0;
}

void LCD1602_Init()
{
    LCD1602_WriteCommand(0x38);
    Delay(5);
    LCD1602_WriteCommand(0x38);
    Delay(5);
    LCD1602_WriteCommand(0x38);
    Delay(5);
    LCD1602_WriteCommand(0x0C);
    LCD1602_WriteCommand(0x06);
    LCD1602_WriteCommand(0x01);
    Delay(5);
}

void LCD1602_SetCursor(unsigned char X,unsigned char Y)
{
    if(X==1){
        LCD1602_WriteCommand(0x80+Y-1);
    }
    else{
        LCD1602_WriteCommand(0xC0+Y-1);
    }
}

void LCD1602_PrintString(unsigned char X,unsigned char Y,unsigned char *String)
{
    LCD1602_SetCursor(X,Y);
    while(*String!='\0'){
        LCD1602_WriteData(*String++);
    }
}

unsigned int pow(unsigned int x,unsigned int y)
{
    unsigned char i;
    unsigned int result=1;
    for(i=0;i<y;i++){
        result*=x;
    }
    return result;
}

void LCD1602_PrintNum(unsigned char X,unsigned char Y,unsigned int Number,unsigned char Length)
{
    unsigned char i;
    LCD1602_SetCursor(X,Y);
    for(i=Length;i>0;i--){
        LCD1602_WriteData(Number/pow(10,i-1)%10+'0');
    }
}

void LCD1602_PrintSignedNum(unsigned char X, unsigned char Y, int Number, unsigned char Length)
{
    unsigned char i;
    LCD1602_SetCursor(X, Y);
    if(Number < 0)
    {
        LCD1602_WriteData('-');
        Number = -Number;
    }
    else
    {
        LCD1602_WriteData('+');
    }
    for(i = Length;i>0;i--)
    {
        LCD1602_WriteData(Number/pow(10,i-1)%10+'0');
    }
}

void LCD1602_PrintHexNum(unsigned char X, unsigned char Y, unsigned int Number, unsigned char Length)
{
    unsigned char i;
    LCD1602_SetCursor(X, Y);
    for(i=Length;i>0;i--)
    {
        if (((Number >> ((i - 1) * 4)) & 0x0F) < 10)
        {
            LCD1602_WriteData(((Number >> ((i - 1) * 4)) & 0x0F) + '0');
        }
        else
        {
            LCD1602_WriteData(((Number >> ((i - 1) * 4)) & 0x0F) - 10 + 'A');
        }
    }
}

void LCD1602_PrintBinNum(unsigned char X, unsigned char Y, unsigned int Number, unsigned char Length)
{
    unsigned char i;
    LCD1602_SetCursor(X,Y);
    for(i=Length;i>0;i--)
    {
        LCD1602_WriteData(((Number >> (i-1)) & 0x01) +'0' );
    }
}